package com.longnuoqi.mydoctor.fragment;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.longnuoqi.mydoctor.activity.DoctorAskActivity;
import com.longnuoqi.mydoctor.adapter.DoctorListViewAdapter;
import com.longnuoqi.mydoctor.entity.Ask;
import com.longnuoqi.mydoctor.utils.FileUtil;
import com.yunhe.mydoctor.R;


import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Lenovo on 2015/12/26.
 */
public class DoctorMoreListFragment extends Fragment {
    private DoctorListViewAdapter adapter;
    private int id;
    private String url;
    private String name;

    private static final int LOAD_START = 1;
    private static final int LOAD_REFRESH = 2;
    private int startList = 0;
    private List<Ask> askList = new ArrayList<>();

    private PullToRefreshListView listView;//对应布局文件中的刷新组件

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.doctor_more_list_layout, container, false);
        savedInstanceState = getArguments();
        id = savedInstanceState.getInt("id");
        url = "http://www.tngou.net/api/ask/list?id=" + id;
        name = "ask_list_" + id + ".txt";
        refresh(view);
        return view;
    }

    private void refresh(View view) {
        listView = (PullToRefreshListView) view.findViewById(R.id.list);
        //对刷新组件进行监听
        listView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> pullToRefreshBase) {
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> pullToRefreshBase) {
                new GetDataTask().execute(LOAD_REFRESH);
            }
        });
        listView.getLoadingLayoutProxy(false, true).setPullLabel("上拉加载...");
        listView.getLoadingLayoutProxy(false, true).setRefreshingLabel("正在加载中...");
        listView.getLoadingLayoutProxy(false, true).setReleaseLabel("松开加载更多...");
        new GetDataTask().execute(LOAD_START);
    }

    private class GetDataTask extends AsyncTask<Integer, Void, List<Ask>> {//异步任务类，三个参数：Void(没有参数),此处一般都放置外部传入的参数；ProgressBar，此处一般放置进度条对象；数据源
        int flag = 0;

        @Override
        protected void onProgressUpdate(Void... values) {
            super.onProgressUpdate(values);
            Toast.makeText(getActivity(), "已是最新数据…", Toast.LENGTH_SHORT).show();
        }

        //子线程请求数据
        @Override
        protected List<Ask> doInBackground(Integer... params) {
            List<Ask> list = new ArrayList<>();
            try {
                flag = params[0];
                String s = "";
                if (!FileUtil.fileIsExist(name)) {
                    Log.e("==============", "doctor more file:" + name + ":is not exist");
                    s = FileUtil.httpGetRequest(url);
                    FileUtil.saveFile(s, name);
                } else {
                    Log.e("==============", "doctor more file:" + name + ":exist");
                    s = FileUtil.readFile(name);
                }
                list = FileUtil.jsonAskList(s);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return list;
        }

        //主线程更新UI
        @Override
        protected void onPostExecute(List<Ask> list) {
            //向刷新组件ListView中，添加一条记录，并刷新该组件
            switch (flag) {
                case LOAD_START:
                    Log.e("===============", "LOAD_START");
                    ListView actualListView = listView.getRefreshableView();//从刷新组件中，获取到刷新后的ListView
                    getActivity().registerForContextMenu(actualListView);//将该ListView，注册到当前上下文
                    if (list.size() < 10) {
                        askList = setList(list, 0, list.size());
                        startList += 10;
                    } else {
                        askList = setList(list, 0, 10);
                        startList += 10;
                    }
                    adapter = new DoctorListViewAdapter(getActivity(), askList);
                    actualListView.setAdapter(adapter);
                    actualListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                            int askId = (int) (view.findViewById(R.id.doctor_item_content_txt)).getTag();
                            Intent intent = new Intent(getActivity(), DoctorAskActivity.class);
                            intent.putExtra("id", askId);
                            startActivityForResult(intent, 0);
                        }
                    });
                    break;
                case LOAD_REFRESH:
                    Log.e("===============", "LOAD_REFRESH");
                    if (list.size() <= 10) {
                        Toast.makeText(getActivity(), "没有更多数据…", Toast.LENGTH_SHORT).show();
                    } else if (list.size() > 10 && list.size() <= 20) {
                        if (startList == 10) {
                            askList.addAll(setList(list, startList, list.size()));
                            startList += 10;
                        } else {
                            Toast.makeText(getActivity(), "没有更多数据…", Toast.LENGTH_SHORT).show();
                        }
                    } else if (list.size() > 20) {
                        if (startList < 20) {
                            askList.addAll(setList(list, startList, startList + 10));
                            startList += 10;
                        } else {
                            Toast.makeText(getActivity(), "没有更多数据…", Toast.LENGTH_SHORT).show();
                        }
                    }
                    break;
            }
            adapter.notifyDataSetChanged();//通知适配器，数据更新已经完成
            listView.onRefreshComplete();
            super.onPostExecute(list);
        }
    }

    private List<Ask> setList(List<Ask> list, int start, int end) {
        List<Ask> askList = new ArrayList<>();
        for (int i = start; i < end; i++) {
            askList.add(list.get(i));
        }
        return askList;
    }
}
